package shuiyuqing.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.R;

import java.util.Stack;

import com.xkh.xkh.MyApplication;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.ImageLoader;

import managers.UIHandler;
import managers.VolleySingleton;
import shuiyuqing.activities.ImageDetail;
import shuiyuqing.activities.WaterActivity;
import shuiyuqing.model.BasicInfoModel;
import shuiyuqing.model.Type;
import shuiyuqing.network.beans.IrrBMSystem;
import shuiyuqing.network.beans.IrrBRStadia;
import shuiyuqing.network.beans.RealTimeIrrBRWaterDam;
import shuiyuqing.network.http.DownloadInfo;
import shuiyuqing.network.http.GetIrrSystemByTime;
import shuiyuqing.views.adapters.WatchPointAdapter;
import utils.TimeUtil;

/**
 * 水情信息界面
 * Created by 凯 on 2015/11/7.
 */
public class WaterFragment extends Fragment implements GetIrrSystemByTime.Delegate {

    Delegate delegate;


    // 最新的实时数据
    RealTimeIrrBRWaterDam realTimeIrrBRWaterDam;

    // 最新的照片数据
    IrrBMSystem irrBMSystem;

    // 当前的照片数据
    IrrBMSystem now_irrBMSystem;

    // 栈
    Stack<IrrBMSystem> stack = new Stack<IrrBMSystem>();

    public Stack<IrrBMSystem> getStack() {
        return stack;
    }

    // 照片时间
    TextView timePhoto;

    // 照片位置
    TextView positionPhoto;

    // 监测点
    View v_point;

    // 监测点名称
    TextView tv_pointName;

    // 渠道名称
    TextView tv_cannelName;

    // 闸门名称
    TextView tv_gateName;

    // 图片
    ImageView img_img;

    // 采集日期
    TextView tv_date;

    // 采集时间
    TextView tv_time;

    // 闸上水位
    TextView tv_upLevel;

    // 闸下数拒
    TextView tv_downLevel;

    // 过闸流量
    TextView tv_flow;

    // 设计水位
    TextView tv_desingWaterLevel;

    // 开闸孔数
    TextView tv_openDot;

    // 开度1
    TextView tv_open1;

    // 开度2
    TextView tv_open2;

    // 开度3
    TextView tv_open3;

    // 开度4
    TextView tv_open4;

    // 开度5
    TextView tv_open5;

    // 操作状态
    TextView tv_operStatus;

    // 图片点击
//    View v_img;

    // 图片,保存图片
    Bitmap bitmap;

    // 查看上一张图片
    View img_back;

    // 查看下一张图片
    View img_next;

    // 标示设计水位和闸上水位
    View v_design;

    View v_realLevel;

    // 设计水位的高度
    int designHeight;

    // 设计水位的值
    TextView tv_designLevel;

    // 实际水位的值
    TextView tv_realLevel;

    // 绘画过
    boolean hasMesured;

    // 包含所有垂直条
    View v_bars;

    // 包含闸门开度的views
    View v_open1;
    View v_open2;
    View v_open3;
    View v_open4;
    View v_open5;

    // 高程
    TextView tv_gangcheng;


    // 闸门下的线
    TextView tv_gate_line1;
    TextView tv_gate_line2;
    TextView tv_gate_line3;
    TextView tv_gate_line4;
    TextView tv_gate_line5;

    // 没有数据
    TextView noneInfo;

    PullToRefreshScrollView pullToRefreshScrollView;

    public TextView getNoneInfo() {
        return noneInfo;
    }

    public TextView getTv_date() {
        return tv_date;
    }

    public int getDesignHeight() {
        return designHeight;
    }

    public View getV_design() {
        return v_design;
    }

    public View getV_realLevel() {
        return v_realLevel;
    }

    public TextView getTv_desingWaterLevel() {
        return tv_desingWaterLevel;
    }

    public TextView getTv_designLevel() {
        return tv_designLevel;
    }

    public TextView getTv_realLevel() {
        return tv_realLevel;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public TextView getTv_cannelName() {
        return tv_cannelName;
    }

    public View getV_bars() {
        return v_bars;
    }

    public void setTv_cannelName(TextView tv_cannelName) {
        this.tv_cannelName = tv_cannelName;
    }

    public View getV_point() {
        return v_point;
    }

    public void setV_point(View v_point) {
        this.v_point = v_point;
    }

    public TextView getTv_pointName() {
        return tv_pointName;
    }

    public ImageView getImg_img() {
        return img_img;
    }

    public TextView getTv_time() {
        return tv_time;
    }

    public TextView getTv_upLevel() {
        return tv_upLevel;
    }

    public TextView getTv_downLevel() {
        return tv_downLevel;
    }

    public TextView getTv_flow() {
        return tv_flow;
    }

    public TextView getTv_openDot() {
        return tv_openDot;
    }

    public TextView getTv_open1() {
        return tv_open1;
    }

    public TextView getTv_open2() {
        return tv_open2;
    }

    public TextView getTv_open3() {
        return tv_open3;
    }

    public TextView getTv_open4() {
        return tv_open4;
    }

    public TextView getTv_open5() {
        return tv_open5;
    }

    public TextView getTv_operStatus() {
        return tv_operStatus;
    }

    public TextView getTv_gateName() {
        return tv_gateName;
    }

    public IrrBMSystem getIrrBMSystem() {
        return irrBMSystem;
    }

    public TextView getTv_gangcheng() {
        return tv_gangcheng;
    }

    public void setTv_gangcheng(TextView tv_gangcheng) {
        this.tv_gangcheng = tv_gangcheng;
    }

    // 设置照片信息
    public void setIrrBMSystem(IrrBMSystem irrBMSystem) {
        this.irrBMSystem = irrBMSystem;
        now_irrBMSystem = irrBMSystem;

        setTimeInfo(now_irrBMSystem);

    }


    public void setTimeInfo(IrrBMSystem now_irrBMSystem)
    {
        if (now_irrBMSystem == null)
            return;
        timePhoto.setText(TimeUtil.getTimeByDate2(now_irrBMSystem.getMeaTime().getTime()));
        if (now_irrBMSystem.getRemark() != null)
        {
            if (now_irrBMSystem.getRemark().endsWith("前"))
            {
                positionPhoto.setText("闸前");
            }
            if (now_irrBMSystem.getRemark().endsWith("后"))
            {
                positionPhoto.setText("闸后");
            }
        }
    }

    public RealTimeIrrBRWaterDam getRealTimeIrrBRWaterDam() {
        return realTimeIrrBRWaterDam;
    }

    public void setRealTimeIrrBRWaterDam(RealTimeIrrBRWaterDam realTimeIrrBRWaterDam) {
        this.realTimeIrrBRWaterDam = realTimeIrrBRWaterDam;
    }


    // 根据闸门设置闸门开度的个数
    public void resetByGateNum(int num) {
        switch (num) {
            case 0:
                v_open1.setVisibility(View.GONE);
                tv_gate_line1.setVisibility(View.GONE);
                v_open2.setVisibility(View.GONE);
                tv_gate_line2.setVisibility(View.GONE);
                v_open3.setVisibility(View.GONE);
                tv_gate_line3.setVisibility(View.GONE);
                v_open4.setVisibility(View.GONE);
                tv_gate_line4.setVisibility(View.GONE);
                v_open5.setVisibility(View.GONE);
                tv_gate_line5.setVisibility(View.GONE);
                break;
            case 1:
                v_open1.setVisibility(View.VISIBLE);
                tv_gate_line1.setVisibility(View.VISIBLE);
                v_open2.setVisibility(View.GONE);
                tv_gate_line2.setVisibility(View.GONE);
                v_open3.setVisibility(View.GONE);
                tv_gate_line3.setVisibility(View.GONE);
                v_open4.setVisibility(View.GONE);
                tv_gate_line4.setVisibility(View.GONE);
                v_open5.setVisibility(View.GONE);
                tv_gate_line5.setVisibility(View.GONE);
                break;
            case 2:
                v_open1.setVisibility(View.VISIBLE);
                tv_gate_line1.setVisibility(View.VISIBLE);
                v_open2.setVisibility(View.VISIBLE);
                tv_gate_line2.setVisibility(View.VISIBLE);
                v_open3.setVisibility(View.GONE);
                tv_gate_line3.setVisibility(View.GONE);
                v_open4.setVisibility(View.GONE);
                tv_gate_line4.setVisibility(View.GONE);
                v_open5.setVisibility(View.GONE);
                tv_gate_line5.setVisibility(View.GONE);
                break;
            case 3:
                v_open1.setVisibility(View.VISIBLE);
                tv_gate_line1.setVisibility(View.VISIBLE);
                v_open2.setVisibility(View.VISIBLE);
                tv_gate_line2.setVisibility(View.VISIBLE);
                v_open3.setVisibility(View.VISIBLE);
                tv_gate_line3.setVisibility(View.VISIBLE);
                v_open4.setVisibility(View.GONE);
                tv_gate_line4.setVisibility(View.GONE);
                v_open5.setVisibility(View.GONE);
                tv_gate_line5.setVisibility(View.GONE);
                break;
            case 4:
                v_open1.setVisibility(View.VISIBLE);
                tv_gate_line1.setVisibility(View.VISIBLE);
                v_open2.setVisibility(View.VISIBLE);
                tv_gate_line2.setVisibility(View.VISIBLE);
                v_open3.setVisibility(View.VISIBLE);
                tv_gate_line3.setVisibility(View.VISIBLE);
                v_open4.setVisibility(View.VISIBLE);
                tv_gate_line4.setVisibility(View.VISIBLE);
                v_open5.setVisibility(View.GONE);
                tv_gate_line5.setVisibility(View.GONE);
                break;
            case 5:
                v_open1.setVisibility(View.VISIBLE);
                tv_gate_line1.setVisibility(View.VISIBLE);
                v_open2.setVisibility(View.VISIBLE);
                tv_gate_line2.setVisibility(View.VISIBLE);
                v_open3.setVisibility(View.VISIBLE);
                tv_gate_line3.setVisibility(View.VISIBLE);
                v_open4.setVisibility(View.VISIBLE);
                tv_gate_line4.setVisibility(View.VISIBLE);
                v_open5.setVisibility(View.VISIBLE);
                tv_gate_line5.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_water, null);

        initview(view);
        initviewwithdata();
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof Delegate) {
            delegate = (Delegate) activity;
        } else {
            System.out.println(activity.getClass().getSimpleName() + " 是否实现了" + Delegate.class.getSimpleName());
        }
    }

    // 初始化界面数据
    private void initviewwithdata() {
        if (delegate != null) {
            IrrBRStadia irrBRStadia = BasicInfoModel.getIrrBRStadiaByCode("10510002");
            if (irrBRStadia != null) {
                delegate.setStadia(irrBRStadia);
            }
        }
    }

    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 点击选择监测点
            if (v == v_point) {
                WatchPointFragment fragment = new WatchPointFragment();
                WatchPointAdapter adapter = new WatchPointAdapter();
                adapter.setType(Type.WATER);
                fragment.setWatchPointAdapter(adapter);
                fragment.show(getFragmentManager(), WatchPointFragment.class.getSimpleName());

            }
            // 点击照片
            else if (v == img_img) {
                if (now_irrBMSystem == null) return;
                String IP = MyApplication.share().getResources().getString(R.string.serverIp);
                String url = "http://" + IP + "/xingkaih/"+ VolleySingleton.encodeUrl(now_irrBMSystem.getFileName());
                Intent intent = new Intent(getActivity(),ImageDetail.class);
                intent.putExtra("url",url);
                getActivity().startActivity(intent);
            }
            // 点击后退
            else if (v == img_back) {
                // 可以回退往前,记录历史，找到前一个
                if (irrBMSystem != null && stack.isEmpty()) {
                    stack.push(irrBMSystem);
                    WaterActivity waterActivity = (WaterActivity) getActivity();
                    new GetIrrSystemByTime(
                            WaterFragment.this,
                            new GetIrrSystemByTime.Upload(waterActivity.getWaterstadia().getStadiaCode(),
                                    irrBMSystem.getMeaTime().getTimeInMillis() + "")).get();
                } else if (now_irrBMSystem != null) {
                    stack.push(now_irrBMSystem);
                    WaterActivity waterActivity = (WaterActivity) getActivity();
                    new GetIrrSystemByTime(
                            WaterFragment.this,
                            new GetIrrSystemByTime.Upload(waterActivity.getWaterstadia().getStadiaCode(),
                                    now_irrBMSystem.getMeaTime().getTimeInMillis() + "")).get();
                } else {
                    Toast.makeText(MyApplication.share(), "已经是最后一个了", Toast.LENGTH_SHORT).show();
                }

            //　点击前进
            } else if (v == img_next) {

                // 获取下个照片信息
                if (!stack.isEmpty()) {
                    now_irrBMSystem = stack.pop();
                    setTimeInfo(now_irrBMSystem);
                    String IP = MyApplication.share().getResources().getString(R.string.serverIp);
                    String url = "http://" + IP + "/xingkaih/"+ VolleySingleton.encodeUrl(now_irrBMSystem.getFileName());
//                    VolleySingleton.getVolleySingleton().displayImg(img_img,url);
                    ImageLoader.getInstance().displayImage(url,img_img,MyApplication.options);

                } else {
                    Toast.makeText(MyApplication.share(), "已经是最新的", Toast.LENGTH_SHORT).show();
                }

            }
        }
    };


    // 清空界面
    public void clear() {
        img_img.setImageResource(R.drawable.defalut_img);

        tv_date.setText("--");
        tv_time.setText("--");
        tv_upLevel.setText("--");
        tv_downLevel.setText("--");
        tv_flow.setText("--");
        tv_openDot.setText("--");
        tv_open1.setText("--");
        tv_open2.setText("--");
        tv_open3.setText("--");
        tv_open4.setText("--");
        tv_open5.setText("--");
        tv_operStatus.setText("--");

        tv_realLevel.setText("");
        tv_designLevel.setText("");

        v_bars.setVisibility(View.GONE);

    }

    // 初始化view
    private void initview(View view) {

        noneInfo = (TextView) view.findViewById(R.id.noneInfo);
        noneInfo.setTypeface(MyApplication.iconfont);
        tv_pointName = (TextView) view.findViewById(R.id.id_tv_pointName);

        timePhoto = (TextView) view.findViewById(R.id.time_img);
        positionPhoto  = (TextView) view.findViewById(R.id.location);

        v_point = view.findViewById(R.id.id_v_sel_point);
        v_point.setOnClickListener(itemClick);

        img_img = (ImageView) view.findViewById(R.id.id_img_img);
        // 点击图片，放大详细显示
        img_img.setOnClickListener(itemClick);

        tv_time = (TextView) view.findViewById(R.id.id_tv_time);
        tv_date = (TextView) view.findViewById(R.id.id_tv_date);

        tv_upLevel = (TextView) view.findViewById(R.id.id_tv_upWaterLevel);

        tv_downLevel = (TextView) view.findViewById(R.id.id_tv_downWaterLevel);

        tv_flow = (TextView) view.findViewById(R.id.id_tv_flow);

        tv_desingWaterLevel = (TextView) view.findViewById(R.id.id_tv_flow31);

        tv_open1 = (TextView) view.findViewById(R.id.id_tv_open1);
        tv_open2 = (TextView) view.findViewById(R.id.id_tv_open2);
        tv_open3 = (TextView) view.findViewById(R.id.id_tv_open3);
        tv_open4 = (TextView) view.findViewById(R.id.id_tv_open4);
        tv_open5 = (TextView) view.findViewById(R.id.id_tv_open5);

        tv_openDot = (TextView) view.findViewById(R.id.id_tv_openDot);
        tv_operStatus = (TextView) view.findViewById(R.id.id_tv_operStatus);

        img_back = view.findViewById(R.id.id_img_back);
        ((TextView)img_back).setTypeface(MyApplication.iconfont);
        img_back.setOnClickListener(itemClick);
        img_next = view.findViewById(R.id.id_img_forword);
        img_next.setOnClickListener(itemClick);
        ((TextView)img_next).setTypeface(MyApplication.iconfont);

        v_design = view.findViewById(R.id.id_v_designLevel);
        v_realLevel = view.findViewById(R.id.id_v_realLevel);


        tv_designLevel = (TextView) view.findViewById(R.id.id_tv_designLevel);
        tv_realLevel = (TextView) view.findViewById(R.id.id_tv_realLevel);

        v_bars = view.findViewById(R.id.id_v_showbar);

        v_open1 = view.findViewById(R.id.id_v_open1);
        v_open2 = view.findViewById(R.id.id_v_open2);
        v_open3 = view.findViewById(R.id.id_v_open3);
        v_open4 = view.findViewById(R.id.id_v_open4);
        v_open5 = view.findViewById(R.id.id_v_open5);

        tv_gate_line1 = (TextView) view.findViewById(R.id.id_tv_line_gate1);
        tv_gate_line2 = (TextView) view.findViewById(R.id.id_tv_line_gate2);
        tv_gate_line3 = (TextView) view.findViewById(R.id.id_tv_line_gate3);
        tv_gate_line4 = (TextView) view.findViewById(R.id.id_tv_line_gate4);
        tv_gate_line5 = (TextView) view.findViewById(R.id.id_tv_line_gate5);


        ViewTreeObserver vto = v_design.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (hasMesured == false) {
                    designHeight = v_design.getMeasuredHeight();
                    hasMesured = true;
//                    v_bars.setVisibility(View.GONE);
                }

                return true;
            }
        });


//        img_img.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                WaterActivity waterActivity = (WaterActivity) getActivity();
//                waterActivity.onTouchEvent(event);
//                return false;
//            }
//        });

        pullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.id_myscroll);
        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                WaterActivity waterActivity = (WaterActivity) getActivity();
                waterActivity.onRefresh();
                pullToRefreshScrollView.onRefreshComplete();
            }
        });

        tv_gangcheng = (TextView) view.findViewById(R.id.id_tv_gaocheng);
        

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bitmap != null)
            bitmap.recycle();
    }

    // 处理获取历史时间回调
    @Override
    public void onResponse(String response, GetIrrSystemByTime getIrrSystemByTime) {
        if (getIrrSystemByTime.getDownload().getStatus() == DownloadInfo.SUCCESS) {
            // 当前的照片信息
            now_irrBMSystem = getIrrSystemByTime.getDownload().getIrrBMSystem();
            setTimeInfo(now_irrBMSystem);

        } else if (getIrrSystemByTime.getDownload().getStatus() == DownloadInfo.FAILED) {

        }
    }

    @Override
    public void onErrorResponse(VolleyError error, GetIrrSystemByTime getIrrSystemByTime) {

    }

    // 回调
    public static interface Delegate {
        public void setStadia(IrrBRStadia irrBRStadia);
    }

    // 根据闸门状态判断是否
    public static void setGateState(TextView tv,char status)
    {
        if (status == '0')
        {
            tv.setText("[无]");
        }
        else if (status == '1')
        {
            tv.setText("[未开]");
        }
        else if (status == '2')
        {

        }
        else if (status == '9')
        {
            tv.setText("[故障]");
        }
    }
}
